﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeaRun.Util;
using LeaRun.Util.WebControl;
using LeaRun.Util.Offices;
using LeaRun.Application.Code;
using System.Threading;
using System.IO;
using LeaRun.Application.Entity.PublicInfoManage;
using LeaRun.Application.Busines.PublicInfoManage;

namespace LeaRun.Application.Web.Controllers
{
    /// <summary>
    /// 版 本
    /// Copyright (c) 2013-2016 上海力软信息技术有限公司
    /// 创建人：佘赐雄
    /// 日 期：2016.2.03 10:58
    /// 描 述：公共控制器
    /// </summary>
    public class UtilityController : Controller
    {
        private FileInfoBLL fileInfoBLL = new FileInfoBLL();
      
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult getCurrentInfo()
        {
            var obj = new
            {
                userId = OperatorProvider.Provider.Current().UserId,
                userName = OperatorProvider.Provider.Current().UserName,
                companyId = OperatorProvider.Provider.Current().CompanyId,
                departmentId = OperatorProvider.Provider.Current().DepartmentId,
                time = DateTime.Now
            };
            return base.Content(obj.ToJson());
        }

        #region 文件操作 
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="fileIdlist"></param>
        /// <returns></returns>
        public ActionResult GetFiles(string fileIdlist)
        {
            if (!string.IsNullOrEmpty(fileIdlist) && fileIdlist != "undefined")
            {
                FileInfoEntity entity = this.fileInfoBLL.GetEntity(fileIdlist);
                string content = string.Concat(new string[]
				{
					"[{\"FileId\":\"",entity.FileId,
					"\",\"FileType\":\"",entity.FileType,
					"\",\"FileName\":\"",entity.FileName,
					"\"}]"
				});
                return base.Content(content);
            }
            return base.Content("[]");
        }
        /// <summary>
        /// 删除文件 
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public ActionResult RemoveFile(string fileId)
        {
            if (!string.IsNullOrEmpty(fileId) && fileId != "undefined")
            {
                FileInfoEntity entity = this.fileInfoBLL.GetEntity(fileId);
                if (System.IO.File.Exists(base.Server.MapPath(entity.FilePath)))
                {
                    System.IO.File.Delete(base.Server.MapPath(entity.FilePath));
                }
            }
            return base.Content("[{\"code\":\"1\"}]");
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileId"></param>
        [HandlerAuthorize(PermissionMode.Enforce), HttpPost]
        public void DownFile(string fileId)
        {
            FileInfoEntity entity = this.fileInfoBLL.GetEntity(fileId);
            string name = base.Server.UrlDecode(entity.FileName);
            string fileName = base.Server.MapPath(entity.FilePath);
            if (FileDownHelper.FileExists(fileName))
            {
                FileDownHelper.DownLoadold(fileName, name);
            }
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="DataItemName"></param>
        /// <param name="Filedata"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadifyFile(string DataItemName, HttpPostedFileBase Filedata)
        {
            ActionResult result;
            try
            {
                Thread.Sleep(500);
                if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
                {
                    result = base.HttpNotFound();
                }
                else
                {
                    string userId = OperatorProvider.Provider.Current().UserId;
                    string random = Guid.NewGuid().ToString();
                    long num = (long)Filedata.ContentLength;
                    string extension = Path.GetExtension(Filedata.FileName);
                    string date = DateTime.Now.ToString("yyyyMMdd");
                    string text3 = string.Format("~/Resource/" + DataItemName + "/{0}/{1}/{2}{3}", userId, date, random, extension);
                    string text4 = base.Server.MapPath(text3);
                    Directory.CreateDirectory(Path.GetDirectoryName(text4));
                    FileInfoEntity fileInfoEntity = new FileInfoEntity();
                    if (!System.IO.File.Exists(text4))
                    {
                        Filedata.SaveAs(text4);
                        fileInfoEntity.Create();
                        fileInfoEntity.FileId = random;
                        fileInfoEntity.FolderId = "0";
                        fileInfoEntity.FileName = Filedata.FileName;
                        fileInfoEntity.FilePath = text3;
                        fileInfoEntity.FileSize = num.ToString();
                        fileInfoEntity.FileExtensions = extension;
                        fileInfoEntity.FileType = extension.Replace(".", "");
                        this.fileInfoBLL.SaveForm("", fileInfoEntity);
                    }
                    result = base.Content("{\"fileId\":\"" + fileInfoEntity.FileId + "\"}");
                }
            }
            catch (Exception ex)
            {
                result = base.Content(ex.Message);
            }
            return result;
        }
        #endregion

        #region 导出Excel
        /// <summary>
        /// 请选择要导出的字段页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ExcelExportForm()
        {
            return View();
        }
        /// <summary>
        /// 执行导出Excel
        /// </summary>
        /// <param name="columnJson">表头</param>
        /// <param name="rowJson">数据</param>
        /// <param name="exportField">导出字段</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        [ValidateInput(false)]
        public void ExecuteExportExcel(string columnJson, string rowJson, string exportField, string filename)
        {
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.Title = Server.UrlDecode(filename);
            excelconfig.TitleFont = "微软雅黑";
            excelconfig.TitlePoint = 15;
            excelconfig.FileName = Server.UrlDecode(filename) + ".xls";
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnEntity = new List<ColumnEntity>();
            //表头
            List<GridColumnModel> columnData = columnJson.ToList<GridColumnModel>();
            //行数据
            DataTable rowData = rowJson.ToTable();
            //写入Excel表头
            string[] fieldInfo = exportField.Split(',');
            foreach (string item in fieldInfo)
            {
                var list = columnData.FindAll(t => t.name == item);
                foreach (GridColumnModel gridcolumnmodel in list)
                {
                    if (gridcolumnmodel.hidden.ToLower() == "false" && gridcolumnmodel.label != null)
                    {
                        string align = gridcolumnmodel.align;
                        excelconfig.ColumnEntity.Add(new ColumnEntity()
                        {
                            Column = gridcolumnmodel.name,
                            ExcelColumn = gridcolumnmodel.label,
                            //Width = gridcolumnmodel.width,
                            Alignment = gridcolumnmodel.align,
                        });
                    }
                }
            }
            ExcelHelper.ExcelDownload(rowData, excelconfig);
        }
        #endregion
    }
}
